﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using LogSystem;
using NodeCanvas.Framework;
using UnityEngine;
using UnityEngine.Serialization;
using XLua;
using Yoozoo.Mars.Got;

namespace Yoozoo.Gameplay.Liberty
{
    // 待后面需求扩展
    [Flags]
    public enum BpTriggerType
    {
        None = 0,
        EnterArea = 1,
        StayArea = 2,
        ExitArea = 4,
    }

    [Flags]
    public enum BpDisableType
    {
        None = 0,
        ExitArea = 1,
    }
    
    [Flags]
    public enum BpTriggerElementType
    {
        None = 0,
        MainPlayer = 1,
    }
    
    public class BlueprintColliderTrigger : MonoBehaviour
    {
        [Header("此区域的ID，对应配表中的ID")]
        public int areaId;
        
        [Header("启用条件类型")]
        public BpTriggerType triggerType = BpTriggerType.EnterArea | BpTriggerType.StayArea;
        [Header("停止条件类型")]
        public BpDisableType disableType = BpDisableType.ExitArea;
        [Header("启用与停止监听的元素类型")]
        public BpTriggerElementType elementType = BpTriggerElementType.MainPlayer;
        
        [SerializeField][DisplayOnly]
        private List<GraphOwner> blueprints;

        [SerializeField][DisplayOnly]
        private bool _bpStatus = false;


        //public Color edgeColor = new Color(1,1,1,1);
        //public Color faceColor = new Color(0, 0, 1, 0.7f);
        
        [SerializeField] 
        private List<Collider> _colliders;
        [SerializeField][DisplayOnly]
        private int enterCount = 0;
        
        public static event Action<BlueprintColliderTrigger> onStateChanged;
        
        private void OnEnable()
        {
            blueprints = GetComponentsInChildren<GraphOwner>().ToList();
            foreach (var blueprint in blueprints)
            {
                blueprint.enableAction = GraphOwner.EnableAction.DoNothing;
            }

            _colliders = GetComponentsInChildren<Collider>().ToList();

            foreach (var col in _colliders)
            {
                BlueprintSubTrigger subTrigger = col.transform.GetOrAddCompoment<BlueprintSubTrigger>();
                subTrigger.onEnter = OnSubTriggerEnter;
                subTrigger.onExit = OnSubTriggerExit;
                subTrigger.onStay = OnSubTriggerStay;
            }
            
            _bpStatus = false;


            StartCoroutine(EnableItor());
            
        }

        IEnumerator EnableItor()
        {
            yield return null;
            onStateChanged?.Invoke(this);
        }

        private void OnSubTriggerEnter(Collider other)
        {
            if ((triggerType & BpTriggerType.EnterArea) > 0 && 
                ((elementType & BpTriggerElementType.MainPlayer)> 0 && BlueprintUtils.IsMainPlayer(other)))
            {
                enterCount++;
                enterCount = Mathf.Max(1, enterCount);
                if(enterCount > 1) return;
                
                foreach (var blueprint in blueprints)
                {
                    if (blueprint.graph.isRunning)
                    {
                        Debug.LogErrorFormat(LogModule.LibertyScene,"该蓝图已经在运行中：{0}",blueprint.transform.name);
                        continue;
                    }
                    
                    blueprint.StartBehaviour();
                    Debug.LogFormat(LogModule.LibertyScene,"启用蓝图：{0}",blueprint.transform.name);
                }

                _bpStatus = true;
            }
        }

        private void OnSubTriggerExit(Collider other)
        {
            if ((disableType & BpDisableType.ExitArea) > 0 && 
                ((elementType & BpTriggerElementType.MainPlayer)> 0 && BlueprintUtils.IsMainPlayer(other)))
            {
                enterCount--;
                if(enterCount > 0) return;
                
                foreach (var blueprint in blueprints)
                {
                    if (!blueprint.graph.isRunning)
                    {
                        continue;
                    }
                    
                    blueprint.StopBehaviour();
                    Debug.LogFormat(LogModule.LibertyScene,"停止蓝图：{0}",blueprint.transform.name);
                }

                _bpStatus = false;
            }
        }

        private void OnSubTriggerStay(Collider other)
        {
            if ((triggerType & BpTriggerType.StayArea) > 0 && 
                ((elementType & BpTriggerElementType.MainPlayer)> 0 && BlueprintUtils.IsMainPlayer(other)))
            {
                if (_bpStatus)
                {
                    return;
                }
                
                foreach (var blueprint in blueprints)
                {
                    if (blueprint.graph.isRunning)
                    {
                        Debug.LogErrorFormat(LogModule.LibertyScene,"该蓝图已经在运行中：{0}",blueprint.transform.name);
                        continue;
                    }
                    
                    blueprint.StartBehaviour();
                    Debug.LogFormat(LogModule.LibertyScene,"启用蓝图：{0}",blueprint.transform.name);
                }

                _bpStatus = true;
            }
        }

#if UNITY_EDITOR

        [BlackList]
        public void ChangeAreaVisible(bool visible)
        {
            foreach (var col in _colliders)
            {
                var mr = col.transform.GetComponent<MeshRenderer>();
                if (mr)
                {
                    mr.enabled = visible;
                }
            }
        }


        private void OnValidate()
        {
            transform.name = "Area_" + areaId.ToString();
        }

        //private List<BoxCollider> _boxColliders;
        //private List<SphereCollider> _sphereColliders;
        
        private void OnDrawGizmosSelected()
        {
            // _boxColliders = GetComponents<BoxCollider>().ToList();
            // _sphereColliders = GetComponents<SphereCollider>().ToList();
            //
            // if (_boxColliders!=null && _boxColliders.Count > 0)
            // {
            //     List<Collider> cols = new List<Collider>(_boxColliders);
            //     Box3D.Render(cols,edgeColor,edgeColor.a,faceColor, faceColor.a,false);
            // }
            //
            // if (_sphereColliders!=null && _sphereColliders.Count > 0)
            // {
            //     List<Collider> cols = new List<Collider>(_sphereColliders);
            //     Sphere3D.Render(cols,edgeColor,edgeColor.a,faceColor, faceColor.a,false);
            // }
            
        }
#endif
        
        
    }
}